package com.mj.mafeed.activity;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.mj.mafeed.R;
import com.mj.mafeed.bean.MemberJSON;
import com.mj.mafeed.service.MemberService;
import com.mj.mafeed.util.Md5Util;
import com.mj.mafeed.util.NetUtils;
import com.mj.mafeed.util.RegUtil;
import com.mj.mafeed.widget.LoadingDialog;
import com.mj.mafeed.activity.MainActivity;
import com.mj.mafeed.util.SPUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * 注册
 * @author zhaominglei
 * @date 2016-2-25
 * 
 */
public class RegisterActivity extends Activity implements OnClickListener {
	@SuppressWarnings("unused")
	private static final String TAG = RegisterActivity.class.getSimpleName();
	public static final int MEMBER_REGISTER_FAIL = 0;
	public static final int MEMBER_REGISTER_SUCCESS = 1;
	private MemberService memberService = new MemberService();
	private ImageView goHome;
	private EditText accountEdt; //手机号
	private String account; //手机号
	private EditText validateCodeEdt; //验证码
	private String validateCode; //验证码
	private Button sendCode; //发送验证码
	private EditText passEdt; //密码
	private String password; //密码
	private EditText cfnpassEdt; //确认密码
	private String cfnpassword; //确认密码
	private Button registerButton; //注册
	private LoadingDialog loadingDialog;
	private int waitSeconds = 60;
	private static final int SENDCODE_START_TIMER = 1;
	private RegisterActivityHandler registerActivityHandler = new RegisterActivityHandler();
	private Timer timer = new Timer(true); //计时器
	private TimerTask task;
	private String postData;
	private Intent intent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		
		init();
	}
	
	private void init() {
		goHome = (ImageView)findViewById(R.id.register_gohome);
		accountEdt = (EditText)findViewById(R.id.register_account_edt);
		validateCodeEdt = (EditText)findViewById(R.id.register_validateCode_edt);
		sendCode = (Button)findViewById(R.id.register_sendCode);
		passEdt = (EditText)findViewById(R.id.register_pass_edt);
		cfnpassEdt = (EditText)findViewById(R.id.register_cfnpass_edt);
		registerButton = (Button)findViewById(R.id.register_register);
		
		goHome.setOnClickListener(this);
		sendCode.setOnClickListener(this);
		registerButton.setOnClickListener(this);
		loadingDialog = new LoadingDialog(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.register_gohome:
			intent = new Intent(getApplicationContext(), MainActivity.class);
			intent.putExtra("referer", "RegisterActivity");
			intent.putExtra("member_register_success", MEMBER_REGISTER_FAIL);
			startActivity(intent);
			RegisterActivity.this.finish();
			break;
		case R.id.register_sendCode:
			sendCode(v);
			break;
		case R.id.register_register:
			register(v);
			break;
		default:
			break;
		}
	}

	private void sendCode(View v) {
		account = accountEdt.getText().toString();
		if (account == null || account.equals("")) {
			Toast.makeText(v.getContext(), R.string.register_account_hint, Toast.LENGTH_SHORT).show();
			return;
		}
		if (!RegUtil.isMobile(account)) {
			Toast.makeText(v.getContext(), R.string.register_account_hint2, Toast.LENGTH_SHORT).show();
			return;
		}
		if (NetUtils.isConnected(getApplicationContext())) {
			loadingDialog.show();
			new SendCodeTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}		
	}

	private void register(View v) {
		account = accountEdt.getText().toString();
		if (account == null || account.equals("")) {
			Toast.makeText(v.getContext(), R.string.register_account_hint, Toast.LENGTH_SHORT).show();
			return;
		}
		if (!RegUtil.isMobile(account)) {
			Toast.makeText(v.getContext(), R.string.register_account_hint2, Toast.LENGTH_SHORT).show();
			return;
		}
		validateCode = validateCodeEdt.getText().toString();
		if (validateCode == null || validateCode.equals("")) {
			Toast.makeText(v.getContext(), R.string.register_validateCode_hint, Toast.LENGTH_SHORT).show();
			return;
		}
		if (validateCode.length() > 6 || !RegUtil.isNumber(validateCode)) {
			Toast.makeText(v.getContext(), R.string.register_validateCode_hint2, Toast.LENGTH_SHORT).show();
			return;
		}
		password = passEdt.getText().toString();
		if (password == null || password.equals("")) {
			Toast.makeText(v.getContext(), R.string.register_pass_hint, Toast.LENGTH_SHORT).show();
			return;
		}
		cfnpassword = cfnpassEdt.getText().toString();
		if (cfnpassword == null || cfnpassword.equals("")) {
			Toast.makeText(v.getContext(), R.string.register_cfnpass_hint, Toast.LENGTH_SHORT).show();
			return;
		}
		if (!cfnpassword.equals(password)) {
			Toast.makeText(v.getContext(), R.string.register_pass_notequals_cfnpass_hint, Toast.LENGTH_SHORT).show();
			return;
		}
		
		if (NetUtils.isConnected(getApplicationContext())) {
			loadingDialog.show();
			StringBuilder param = new StringBuilder();
			param.append("username=").append(account).append("&password=").append(Md5Util.encrypt(password));
			param.append("&validateCode=").append(validateCode);
			postData = param.toString();
			new RegisterTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onBackPressed() {
		intent = new Intent(getApplicationContext(), MainActivity.class);
		intent.putExtra("referer", "RegisterActivity");
		intent.putExtra("member_register_success", MEMBER_REGISTER_FAIL);
		startActivity(intent);
		RegisterActivity.this.finish();
	}
	
	public class SendCodeTask extends AsyncTask<String, String, Boolean> {
		@Override
		protected Boolean doInBackground(String... params) {
			return memberService.sendCode(getApplicationContext(), "RegisterActivity", account);
		}
		@Override
		protected void onPostExecute(Boolean result) {
			loadingDialog.dismiss();
			sendCode.setClickable(false);
			sendCode.setText(String.valueOf(waitSeconds));
			task = new TimerTask() {
				@Override
				public void run() {
					Message msg = new Message();
					msg.what = SENDCODE_START_TIMER;
					registerActivityHandler.sendMessage(msg);
				}
			};
			timer.schedule(task, new Date(), 1000);
		}
	}
	
	@SuppressLint("HandlerLeak")
	public class RegisterActivityHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SENDCODE_START_TIMER:
				waitSeconds--;
				sendCode.setText(String.valueOf(waitSeconds));
				if (waitSeconds == 0) {
					task.cancel();
					waitSeconds = 60;
					sendCode.setText(R.string.sendCode);
					sendCode.setClickable(true);
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	}
	
	public class RegisterTask extends AsyncTask<String, String, MemberJSON> {
		@Override
		protected MemberJSON doInBackground(String... params) {
			return memberService.register(postData);
		}

		@Override
		protected void onPostExecute(MemberJSON result) {
			if (result == null) {
				Toast.makeText(getApplicationContext(), R.string.register_error, Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(), R.string.register_success, Toast.LENGTH_SHORT).show();
			}
			SPUtils.put(getApplicationContext(), "member", result);
			intent = new Intent(getApplicationContext(), MainActivity.class);
			intent.putExtra("referer", "RegisterActivity");
			intent.putExtra("member_register_success", MEMBER_REGISTER_SUCCESS);
			startActivity(intent);
			RegisterActivity.this.finish();
			loadingDialog.dismiss();
		}
	}
}
